/**
 * 运行配置 
 */
const Conf =  require('./config')
const Koa = require('koa')
const app = new Koa()
const logger = require('koa-logger')
const error = require('koa-error')
const bodyParser = require('koa-bodyparser')
const Pug = require('koa-pug')
const serve = require('koa-static');
const convert = require('koa-convert')

/**
 * pug
 */
const pug = new Pug({
  viewPath: './views',
  debug: false,
  pretty: false,
  compileDebug: false,
  locals: '',
  helperPath: [],
  app: app
})
pug.locals = Object.assign(pug.locals, {
  sitename: Conf.siteName
})

/**
 * middleware
 */

app.use(logger())
app.use(bodyParser())

app.use(error({
  engine: Conf.engine,
  template: __dirname + '/views/error.pug'
}))

/**
 * database
 */
const database = require('./config/database')
try {
  database.connect()
} catch (error) {
  console.log(error)
}
/**
 * 静态文件夹
 */
app.use(convert(serve(__dirname + '/static')))

/**
 * stylus
 */

/**
 * 路由
 */
const api = require('./routes/api')
const web = require('./routes/web')
app.use(api.routes())
app.use(web.routes())

app.listen(Conf.port, () => {
  console.log(`the serve is runing at port ${Conf.port}`)
})

module.exports = app